package com.woniu.tms.web.AOP;

import com.woniu.tms.entity.Logform;
import com.woniu.tms.entity.User;
import com.woniu.tms.manage.service.LogService;
import com.woniu.tms.mapper.LogformMapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

@Aspect
@Configuration
public class LogAOP {

    @Autowired
    LogformMapper LogformMapper;

    @Pointcut("" +
            "execution(* com.woniu.tms.manage.service..*.*(..))||" +
            "execution(* com.woniu.tms.attendance.service..*.*(..))||" +
            "execution(* com.woniu.tms.exam.service..*.*(..))||" +
            "execution(* com.woniu.tms.interview.service..*.*(..))||" +
            "execution(* com.woniu.tms.studentinfo.service..*.*(..))||" +
            "execution(* com.woniu.tms.openclass.service..*.*(..))")
    public void pointCut() {
    }

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint pjp) {
        Object obj = null;
        try {
            obj = pjp.proceed();
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            // 得到session
            HttpSession session = request.getSession();
            User loginUser = (User) session.getAttribute("loginUser");
            // 执行哪个类中的方法
            String cls = pjp.getTarget().getClass().getName();
            // 执行的方法名
            String method = pjp.getSignature().getName();
            // 增加日志记录
            // 如果不是查询方法就记录操作日志
            if (!method.contains("get") && !method.contains("index") && !method.contains("list") && !method.contains("fin") && !method.contains("UWB") && !method.contains("EWB")) {
                Logform logform = new Logform();
                logform.setDotime(new Date());
                logform.setUid(loginUser.getUid());
                logform.setInfo(loginUser.getUname() + "执行了" + cls + "类中的" + method + "方法");
                LogformMapper.insert(logform);
            }
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            throw new RuntimeException(throwable.getMessage());
        }
        return obj;
    }

}
